library IEEE;
use IEEE.STD_LOGIC_1164.ALL;


use WORK.FAW_TYPES.ALL;



entity Source is
    Port ( clk_s : in  std_logic;
           pixel_merged_s : in  std_logic_vector (23 downto 0);   
           frame_valid_s : out  std_logic;
           line_valid_s : out  std_logic;
           pixel_valid_s : out  std_logic;
           left_out_s : out  STD_LOGIC_VECTOR (7 downto 0);
           right_out_s : out  STD_LOGIC_VECTOR (7 downto 0)
		);
end Source;

architecture Behavioral of Source is


begin

	processo: process(clk_s)
	
	variable ROWS_COUNTER: integer:= 0;
	variable COLUMNS_COUNTER: integer:= 0;
	variable FRAME_VALID_VAR: std_logic:='0';
	variable LINE_VALID_VAR: std_logic:='0';
	variable PIXEL_VALID_VAR: std_logic:='0';
	variable COUNTER: integer:=3; 
	variable LEFT_OUT_VAR: STD_LOGIC_VECTOR (7 downto 0);
	variable RIGHT_OUT_VAR: STD_LOGIC_VECTOR (7 downto 0);
	
	begin
	
	if (clk_s'event and clk_s='1') then
		if (ROWS_COUNTER=0) and (COLUMNS_COUNTER=0)  then
			if (COUNTER=3) and (FRAME_VALID_VAR='0') then
					FRAME_VALID_VAR:='1';
					COUNTER:=0;
			elsif (FRAME_VALID_VAR='1') then
					LINE_VALID_VAR:='1';
					PIXEL_VALID_VAR:='1';
					ROWS_COUNTER:=1;
			end if;
		
	end if;
	
	if (COLUMNS_COUNTER=W) then
		if (COUNTER=1) then
			PIXEL_VALID_VAR:='0';
			LINE_VALID_VAR:='0';
			if (ROWS_COUNTER=H) then
				FRAME_VALID_VAR:='0';
				COLUMNS_COUNTER:=0;
				ROWS_COUNTER:=0;
			end if;
		elsif (COUNTER=3) then
			COUNTER:=0;
			COLUMNS_COUNTER:=0;
			ROWS_COUNTER:=ROWS_COUNTER+1;
			LINE_VALID_VAR:='1';
			PIXEL_VALID_VAR:='1';
		end if;
	end if;
	
	
	if(PIXEL_VALID_VAR='1') then
		COLUMNS_COUNTER:=COLUMNS_COUNTER+1;
	end if;
		
		--Campionamento del pixel (DA CONTROLLARE!!!!)
		LEFT_OUT_VAR:=pixel_merged_s(23 downto 16);
		RIGHT_OUT_VAR:=pixel_merged_s(15 downto 8);
		
	end if;
	
	if (clk_s'event and clk_s='0') then
		
		if(COLUMNS_COUNTER=W) and (ROWS_COUNTER<H) and (COUNTER<3) then
			COUNTER:=COUNTER+1;
		end if;
		
		if (ROWS_COUNTER=H) and (COLUMNS_COUNTER=W) and (COUNTER=0)  then
			COUNTER:=COUNTER+1;
		end if;
		
		if (ROWS_COUNTER=0) and (COLUMNS_COUNTER=0) and (COUNTER<3) and (FRAME_VALID_VAR='0')  then
			COUNTER:=COUNTER+1;
		end if;
		
	end if;

	
	frame_valid_s<= FRAME_VALID_VAR;
	line_valid_s<= LINE_VALID_VAR;
	pixel_valid_s<= PIXEL_VALID_VAR;
	right_out_s<= RIGHT_OUT_VAR;
	left_out_s<=LEFT_OUT_VAR;
	
   end process processo;

end Behavioral;

